const puppeteer = require('puppeteer');
const path = require('path');

async function renderCard() {
    let browser;
    try {
        console.log('Launching browser...');
        browser = await puppeteer.launch({
            headless: true, // 使用新的无头模式
            args: ['--no-sandbox', '--disable-setuid-sandbox'] // 在某些环境可能需要
        });
        console.log('Browser launched.');

        const page = await browser.newPage();
        console.log('New page created.');

        // 构建HTML文件的绝对路径
        // 假设 deepseek_html_20250605_fb6f8f.html 与 card_renderer_puppeteer 目录在同一父目录下
        const htmlFilePath = path.resolve(__dirname, '../deepseek_html_20250605_fb6f8f.html');
        const localFileUrl = `file://${htmlFilePath}`;

        console.log(`Navigating to ${localFileUrl}...`);
        await page.goto(localFileUrl, {
            waitUntil: 'networkidle0' // 等待网络空闲，确保所有资源加载完毕
        });
        console.log('Page loaded.');

        // 设置视口大小，可以根据名片实际尺寸调整
        await page.setViewport({ width: 400, height: 900 }); // 稍微比名片大一点确保完整捕获

        console.log('Locating card element...');
        const cardElement = await page.$('#business-card');

        if (cardElement) {
            console.log('Card element found. Taking screenshot...');
            const outputPath = path.resolve(__dirname, 'business_card.png');
            await cardElement.screenshot({
                path: outputPath,
                omitBackground: true // 如果你想让HTML的背景透明，这个可能有用，但你的名片本身有背景色
            });
            console.log(`Screenshot saved to ${outputPath}`);
        } else {
            console.error('Could not find element with ID #business-card on the page.');
        }

    } catch (error) {
        console.error('Error during card rendering:', error);
    } finally {
        if (browser) {
            console.log('Closing browser...');
            await browser.close();
            console.log('Browser closed.');
        }
    }
}

renderCard(); 